#include "hfgl/hfgl_point.h"
#include "svgloader/svgloader.h"
#include "svgloader/svg_exception.h"
#include "common.h"
#include "svgloader/svg_polygon_path.h"
#include "hfgl/hfgl_surface.h"

#include <stdio.h>

svgloader::svgloader(std::string filename)
{
    TiXmlDocument doc(filename.c_str());
    if (!doc.LoadFile())
        throw svg_exception(ENG_OBJECT_FILE_OPEN_ERROR, filename.c_str());

    TiXmlElement* pElem = doc.FirstChildElement();
    
    if (!pElem)
        throw svg_exception(ENG_OBJECT_FILE_WRONG_ERROR, " Elements not found.");
    
    if (strcmp("svg", pElem->Value()))
        throw svg_exception(ENG_OBJECT_FILE_WRONG_ERROR, " First element is not SVG.");

    m_width = svg_getFloatFromStr(common::xml_getAttribute(pElem, "width"));
    m_height = svg_getFloatFromStr(common::xml_getAttribute(pElem, "height"));

    for (TiXmlElement* child = pElem->FirstChildElement(); child; child = child->NextSiblingElement())
        addPolygon(child);
}

float svgloader::svg_getFloatFromStr(std::string value)
{
    size_t pt = value.find("pt");
    if (pt != std::string::npos)
        value = value.substr(0, pt);
    
    return atof(value.c_str());
}

svgloader::~svgloader()
{
    for(std::vector<svg_polygon*>::iterator it = m_polygons.begin(); it != m_polygons.end(); it++)
        delete (*it);
}

hfgl_picture* svgloader::getPicture()
{
    hfgl_surface** surfaces = new hfgl_surface*[m_polygons.size()];
    
    int i = 0;
    for(std::vector<svg_polygon*>::iterator it = m_polygons.begin(); it != m_polygons.end(); it++)
    {
        surfaces[i] = (*it)->getSurface(30);
        i++;
    };
    
    return new hfgl_picture(m_polygons.size(), surfaces);
}

void svgloader::addPolygon(TiXmlElement* child)
{
    svg_polygon* newPoly = NULL;
    // Исходя из типа выбираю соответствующий объект
    if (!strcmp("line", child->Value()))
        newPoly = new svg_polygon(child);
    else if (!strcmp("circle", child->Value()))
        newPoly = new svg_polygon(child);
    else if (!strcmp("path", child->Value()))
        newPoly = new svg_polygon_path(child);
    
    if (newPoly)
        m_polygons.push_back(newPoly);    
}